/**
 * 
 */
package three_star_craft.uap.state;

import java.io.InputStream;

import org.grlea.log.SimpleLogger;

import three_star_craft.sound.AudioPlayer;
import three_star_craft.uap.UapGenerator;
import three_star_craft.uap.event.EventUapMediaBearerSetupCfm;
import three_star_craft.uap.timer.TimerEvent;

/**
 * Class representing state when generator has initiated
 * setup of media bearer towards Media Gateway
 * 
 * @author w.antosiewic
 *
 */
public class UapStateMediaBearerSetupPend extends UapStateBase
{
    private static final SimpleLogger logger =
            new SimpleLogger(UapStateMediaBearerSetupPend.class);
    
    private static UapStateMediaBearerSetupPend instance =
            new UapStateMediaBearerSetupPend();
    
    /**
     * Return singleton instance of this state
     * @return an instance of this state
     */
    public static UapStateMediaBearerSetupPend getInstance()
    {
        return instance;
    }
    
    /**
     * Creates an instance of this class 
     */
    private UapStateMediaBearerSetupPend()
    {
        super("MediaBearerSetupPend");
    }
    
    
    /* (non-Javadoc)
     * @see three_star_craft.uap.state.UapStateBase#handleUapTimerWaitForMediaBearerCfm(three_star_craft.uap.UapGenerator, three_star_craft.uap.timer.TimerEvent)
     */
    @Override
    public void handleUapTimerWaitForMediaBearerCfm(
            UapGenerator uapGenerator,
            TimerEvent event)
    {
        logger.debug("MediaBearer setup timed out, generatorId=0x"+
                Integer.toHexString(uapGenerator.getGeneratorId()));
        
        uapGenerator.changeState(UapStateMap.UAP_CONNECTED);
        uapGenerator.getUapConnectionListener().
            mediaBearerSetupTimeout(uapGenerator);
    }

    /* (non-Javadoc)
     * @see three_star_craft.uap.state.UapStateBase#handleUapMediaBearerSetupConfirm(three_star_craft.uap.UapGenerator, three_star_craft.uap.event.EventUapMediaBearerSetupCfm)
     */
    @Override
    public void handleUapMediaBearerSetupConfirm(
            UapGenerator generator,
            EventUapMediaBearerSetupCfm event)
    {
        generator.cancelTWaitForMediaBearerCfm();
        generator.changeState(UapStateMap.UAP_CONNECTED);
        
        generator.getUapConnectionListener().mediaBearerSetupConfirmInd(generator);
        
        if(!generator.connectMediaSocket(event.getServerMediaAddress(),
                                         event.getServerMediaPort()))
        {
            logger.debugObject("Failed to connect to MediaGateway, generatorId=0x",
                        Integer.toHexString(generator.getGeneratorId()));
            return;
        }
        InputStream mediaStream = generator.getMediaStream();
        if(mediaStream == null)
        {
            logger.error("Failed to obtain media stream");
            return;
        }
        AudioPlayer.instance().setupLine(mediaStream);
    }
    
    
}
